package result

import (
	"fmt"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"go_zero_blog/common/xerr"
	"net/http"
)

func HttpResult(r *http.Request, w http.ResponseWriter, resp interface{}, err error) {
	if err == nil {
		r := Success(resp)
		httpx.WriteJson(w, http.StatusOK, r)
	} else {
		//	 错误返回
		errCode := xerr.ServerError
		errMsg := xerr.DefaultMsg
		var e *xerr.CodeError
		if errors.As(err, &e) {
			errCode = e.GetErrCode()
			errMsg = e.GetErrMsg()
		}
		logx.WithContext(r.Context()).Errorf("【API-ERR】: %+v", err)
		httpx.WriteJson(w, http.StatusInternalServerError, Error(errCode, errMsg))
	}
}

func ParamErrorResult(r *http.Request, w http.ResponseWriter, err error) {
	errMsg := fmt.Sprintf("%s,%s", xerr.MapErrMsg(xerr.ParamError), err.Error())
	httpx.WriteJson(w, http.StatusBadRequest, Error(xerr.ParamError, errMsg))
}
